package com.jws.battleship;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBSavedGames
{
	public static final int GAME_TABLE_ID = 0;
	public static final int GAME_TABLE_CREATED = 1;
	public static final int GAME_TABLE_TURN = 2;
	public static final int GAME_TABLE_SHOTS = 3;
	public static final int GAME_TABLE_MY_SHIPS = 4;
	public static final int GAME_TABLE_OPP_SHIPS = 5;
	public static final int GAME_TABLE_OPPONENTS = 6;
	
	public static final int FRIEND_TABLE_ID = 0;
	public static final int FRIEND_TABLE_NAME = 1;
	public static final int FRIEND_TABLE_RANK = 2;
	
	private static final String DATABASE_NAME = "BattleShipSavedGames.db";
	private static final String DATABASE_TABLE_GAME = "SavedGame";
	private static final String DATABASE_TABLE_FRIEND = "Friend";
	private static final int DATABASE_VERSION = 1;
	private SQLiteDatabase db;
	private final Context context;
	private DBOpenHelper dbHelper;
	
	//Column names
	public static final String KEY_GAME_ID = "_id";
	public static final String KEY_GAME_CREATED = "gameCreatedDate";
	public static final String KEY_GAME_TURN = "gameTurn";
	public static final String KEY_GAME_SHOTS = "gameShots";
	public static final String KEY_GAME_MY_SHIPS = "gameMyShips";
	public static final String KEY_GAME_OPPONENTS_SHIPS = "gameOppShips";
	public static final String KEY_GAME_OPPONENTS = "gameOpponents";
	
	public static final String KEY_FRIEND_ID = "_id";
	public static final String KEY_FRIEND_NAME = "friendName";
	public static final String KEY_FRIEND_RANK = "friendRank";
	
	public DBSavedGames(Context _context) 
	{
		this.context = _context;
		dbHelper = new DBOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
	}
	
	/**
	 * Closes the connection to the database.
	 */
	public void close() 
	{
		db.close();
	}
	
	/**
	 * Open the connection to the database.
	 * @throws SQLiteException If it can't open a writable database connection it will try to open a readable connection.
	 */
	public void open() throws SQLiteException 
	{
		try 
		{
			db = dbHelper.getWritableDatabase();
		} 
		
		catch (SQLiteException ex) 
		{
			db = dbHelper.getReadableDatabase();
		}
	}
	
	/**
	 * Open the connection to the database in read only mode.
	 * @throws SQLiteException If it can't open a database connection.
	 */
	public void openReadOnly() throws SQLiteException 
	{
		try 
		{
			db = dbHelper.getReadableDatabase();
		} 
		
		catch (SQLiteException ex) 
		{
			throw new SQLException("Can't open the database.");
		}
	}
	
	/**
	 * Insert a new patient in the database
	 * @param The patient to insert.
	 * @return The row ID of the newly inserted row, or -1 if an error occurred. 
	 */
	public long insertGame(Game game) 
	{
		// Create a new row of values to insert.
		ContentValues newValues = new ContentValues();
		
		String test = game.getOpponentsIDs(); //TODO her skal den have fat i IDerne i stedet for friend objekterne.
		
		// Assign values for each row.
		newValues.put(KEY_GAME_CREATED, game.getPersistableDate());
		newValues.put(KEY_GAME_TURN, game.getTurn());
		newValues.put(KEY_GAME_SHOTS, Coordinate.coordinateListToString(game.getShots()));
		newValues.put(KEY_GAME_MY_SHIPS, Ship.shipListToString(game.getMyShips()));
		newValues.put(KEY_GAME_OPPONENTS_SHIPS, Ship.shipListToString(game.getOpponentsShips()));
		newValues.put(KEY_GAME_OPPONENTS, Friend.friendListToString(game.getOpponents()));
		
		// Insert the row.
		return db.insert(DATABASE_TABLE_GAME, null, newValues);
	}
	
	public long insertFriend(Friend friend) 
	{
		// Create a new row of values to insert.
		ContentValues newValues = new ContentValues();
		
		// Assign values for each row.
		newValues.put(KEY_FRIEND_NAME, friend.getName());
		newValues.put(KEY_FRIEND_RANK, friend.getRank());
		
		// Insert the row.
		return db.insert(DATABASE_TABLE_FRIEND, null, newValues);
	}
	
	/**
	 * Remove a patient based on its cpr number.
	 * @param The patient to remove.
	 * @return Returns if it succeeded.
	 */
//	public boolean removePatient(Patient _patient) 
//	{
//		try 
//		{
//			Cursor c = getPatient(_patient.getCPR());
//			long rowIndex = Long.parseLong(c.getString(0));
//			
//			return db.delete(DATABASE_TABLE, KEY_ID + "=" + rowIndex, null) > 0;
//		} 
//		
//		catch (Exception e) {
//			return false;
//		}
//	}
	
	/**
	 * Update a patients saved data. If the patient does not exist, it will try to insert the patient (as a new one).
	 * @param The patient to update.
	 * @return If it went well
	 */
//	public boolean updatePatient(Patient _patient) 
//	{		
//		try 
//		{
//			Cursor c = getPatient(_patient.getCPR());
//			String test = c.getString(0);
//			long rowIndex = Long.parseLong(test);
//			
//			ContentValues newValue = new ContentValues();
//			
//			newValue.put(KEY_PATIENT_NAME, _patient.getName());
//			newValue.put(KEY_PATIENT_CPR, _patient.getCPR());
//			newValue.put(KEY_PATIENT_NOTE, _patient.getNote());
//			newValue.put(KEY_PATIENT_UPDATED_DATE, _patient.getLastUpdated().getTime());
//			newValue.put(KEY_TOKS_CONSCIOUSNESS, _patient.getTOKS().getConsciousness());
//			newValue.put(KEY_TOKS_DIASTOLIC, _patient.getTOKS().getBloodPressureDiastolic());
//			newValue.put(KEY_TOKS_HEART_RATE, _patient.getTOKS().getHeartRate());
//			newValue.put(KEY_TOKS_OXYGEN, _patient.getTOKS().getOxygenLitersPerMinute());
//			newValue.put(KEY_TOKS_RESPIRATION, _patient.getTOKS().getRespirationFrequency());
//			newValue.put(KEY_TOKS_SATURATION, _patient.getTOKS().getSaturation());
//			newValue.put(KEY_TOKS_SYSTOLIC, _patient.getTOKS().getBloodPressureSystolic());
//			newValue.put(KEY_TOKS_TEMPERATURE, _patient.getTOKS().getTemperature());
//			newValue.put(KEY_TOKS_TOTAL_SCORE, _patient.getTOKS().getTotalScore());
//			
//			return db.update(DATABASE_TABLE, newValue, KEY_ID + "=" + rowIndex, null) > 0;
//		}
//		
//		catch (Exception e) 
//		{
//			if(insertPatient(_patient) != -1)
//				return true;
//			else 
//				return false; 
//		}
//	}
	
	/**
	 * Find all patients in the database
	 * @return returns a cursor to the objects
	 */
	public Cursor getAllItemsCursor() 
	{
		return db.query(DATABASE_TABLE_GAME,
				new String[] {KEY_GAME_ID, 
								KEY_GAME_CREATED, 
								KEY_GAME_TURN,
								KEY_GAME_SHOTS,
								KEY_GAME_MY_SHIPS,
								KEY_GAME_OPPONENTS_SHIPS,
								KEY_GAME_OPPONENTS},
		null, null, null, null, null);
	}
	
	public Cursor getAllFriends() 
	{
		return db.query(DATABASE_TABLE_FRIEND,
				new String[] {KEY_FRIEND_ID, 
								KEY_FRIEND_NAME, 
								KEY_FRIEND_RANK},
		null, null, null, null, null);
	}
	
	/**
	 * Get a specific patient
	 * @param The cpr number of the patient to find.
	 * @return returns a cursor to the patient in the database
	 * @throws SQLException throws if nothing found on the specified row index
	 */
	/*public Cursor getPatient(String _cpr) throws SQLException 
	{
		Cursor result = db.query(true, DATABASE_TABLE_GAME, new String[] {KEY_ID, 
				KEY_PATIENT_NAME, 
				KEY_PATIENT_CPR, 
				KEY_PATIENT_NOTE, 
				KEY_PATIENT_UPDATED_DATE, 
				KEY_TOKS_RESPIRATION, 
				KEY_TOKS_SYSTOLIC, 
				KEY_TOKS_HEART_RATE, 
				KEY_TOKS_TEMPERATURE, 
				KEY_TOKS_SATURATION, 
				KEY_TOKS_DIASTOLIC, 
				KEY_TOKS_CONSCIOUSNESS, 
				KEY_TOKS_OXYGEN, 
				KEY_TOKS_TOTAL_SCORE},
				KEY_PATIENT_CPR + "=" + _cpr, null, null, null, null, null);
		
		if ((result.getCount() == 0) || !result.moveToFirst()) 
		{
			throw new SQLException("No patient found with cpr: " + _cpr);
		}
		
		return result;
	}*/
	
	/**
	 * Get the number of patients in the database.
	 * @return Returns the number of patients in the database.
	 */
	/*public Integer getPatientCount()
	{
		Cursor result = db.query(true, DATABASE_TABLE_GAME, new String[] {KEY_ID, KEY_PATIENT_NAME},
				null, null, null, null, null, null);
		
		return result.getCount();
	}*/
	
	private static class DBOpenHelper extends SQLiteOpenHelper {
		public DBOpenHelper(Context context, String name, CursorFactory factory, int version) 
		{
			super(context, name, factory, version);
		}
		
		// SQL Statement to create a new database.
		private static final String DATABASE_CREATE_GAME = "create table " +
			DATABASE_TABLE_GAME + " (" + 
			KEY_GAME_ID + " integer primary key autoincrement, " +
			KEY_GAME_CREATED + " text, " + 
			KEY_GAME_TURN + " text, " +
			KEY_GAME_SHOTS + " text, " +
			KEY_GAME_MY_SHIPS + " text, " +
			KEY_GAME_OPPONENTS_SHIPS + " text, " +
			KEY_GAME_OPPONENTS + " text);";
		
		private static final String DATABASE_CREATE_FRIEND = "create table " +
			DATABASE_TABLE_FRIEND + " (" + 
			KEY_FRIEND_ID + " integer primary key autoincrement, " +
			KEY_FRIEND_NAME + " text, " + 
			KEY_FRIEND_RANK + " integer);";
		
		//TODO
//		private static final String DATABASE_CREATE_GAME_SHOTSr = "create table " +
//				DATABASE_TABLE_GAME + " (" + 
//				KEY_ID + " integer primary key autoincrement, " +
//				KEY_PATIENT_NAME + " text not null, " + 
//				KEY_PATIENT_CPR + " text not null, " +
//				KEY_PATIENT_NOTE + " text, " +
//				KEY_PATIENT_UPDATED_DATE + " text, " +
//				KEY_TOKS_RESPIRATION + " Integer, " +
//				KEY_TOKS_SYSTOLIC + " Integer, " +
//				KEY_TOKS_HEART_RATE + " Integer, " +
//				KEY_TOKS_TEMPERATURE + " Double, " +
//				KEY_TOKS_SATURATION + " Integer, " +
//				KEY_TOKS_DIASTOLIC + " Integer, " +
//				KEY_TOKS_CONSCIOUSNESS + " text, " +
//				KEY_TOKS_OXYGEN + " Double, " +
//				KEY_TOKS_TOTAL_SCORE + " Integer);";	
		
		@Override
		public void onCreate(SQLiteDatabase _db) 
		{
			_db.execSQL(DATABASE_CREATE_GAME);
			_db.execSQL(DATABASE_CREATE_FRIEND);
		}
		
		@Override
		public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) 
		{
			Log.w("TaskDBAdapter", "Upgrading from version " +
			_oldVersion + " to " +
			_newVersion + ", which will destroy all old data");
			
			// Drop the old table.
			_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_GAME);
			_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_FRIEND);
			
			// Create a new one.
			onCreate(_db);
		}
	}
	
}